<?php

class PostController extends Controller {
	public function index() {
		$err = array();
		$warn = "";
		$clean_html = "";
		$clean_title = "";
		$cate = 0;
		$this->_set_model("post");
		if (isset($_POST["submit"]) && $_POST["submit"]) {
			$title = $_POST['title'];
			$dirty = $_POST['post_content'];
			$cate = $_POST["category"];
			// 净化 HTML, 防止 XSS 攻击
			$config = HTMLPurifier_Config::createDefault();
			$purifier = new HTMLPurifier($config);
			$clean_html = $purifier->purify($dirty);
			$clean_title = $purifier->purify($title);
			if (empty($clean_title)) {
				$err[] = "文章标题不能为空。";
			}
			if (empty($clean_html)) {
				$err[] = "文章内容不能为空。";
			}
			$warn = "发表文章失败，发生了以下错误：";
			// 发表成功后跳转到成功页面
			if (empty($err)) {
				if ($this->_model->send_post($cate, $clean_title, $clean_html)) {
					$this->success();
					exit();
				} else {
					$err[] = "文章数据库异常。";
				}
			}
		}
		list($cids, $cnames) = $this->_model->get_categories();
		$this->_view->set("warning", $warn);
		$this->_view->set("errors", $err);
		$this->_view->set("category_ids", $cids);
		$this->_view->set("category_names", $cnames);

		$this->_view->set("h_cate_ids", $cids);
		$this->_view->set("h_cate_names", $cnames);

		// 实现 sticky form
		$this->_view->set("old_content", $clean_html);
		$this->_view->set("old_title", $clean_title);
		$this->_view->set("old_category", $cate);

		$this->_view->set("page_title", SITE_NAME);
		$this->_view->load('header.php');
		$this->_view->load('post/postview.php');
		$this->_view->load('footer.php');
		$this->_view->display();
	}

	private function success() {
		list($hci, $hcn) = $this->_model->get_categories();
		$this->_view->set("h_cate_ids", $hci);
		$this->_view->set("h_cate_names", $hcn);

		$this->_view->set("page_title", SITE_NAME);
		$this->_view->load('header.php');
		$this->_view->load('post/successview.php');
		$this->_view->load('footer.php');
		$this->_view->display();
	}
}